<template>
    <div>
        <h1>{{ title }}</h1>
        <div class="editor-shell">
            <button @click="getSection">获取 section</button>
            <button @click="setSelection">设置选区dom 选中节点全部文本</button>
            <button @click="setSelectionText">设置选区文本 选中节点部分文本</button>
            <button @click="setSelectionText2">设置选区文本  跨节点 选中部分文本</button>
        </div>
        <div>
            <p>section 页面</p>
            <div class="editor" contenteditable="">
                <span>测试实测1</span>
                <br/>
                <span>测试实测2</span>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ref } from 'vue'

const title = ref('section')
const getSection = () => {
    const activeElement = document.activeElement;
    console.log(activeElement)
    const dom = document.querySelector('.editor')
    const section = window.getSelection()   
    const selectText = section.toString()
    const range = section.getRangeAt(0)
    console.log(dom)
    console.log(section)
    console.log(range)
    console.log(selectText)
}

const setSelection = () => {
    const dom = document.querySelector('.editor')
    const selection = window.getSelection()
    const range = document.createRange()
    range.selectNode(dom)
    selection.removeAllRanges()
    selection.addRange(range)
}
const setSelectionText = () => {
    const selection = window.getSelection()
    selection.removeAllRanges()
    const range = document.createRange()
    const textNode = document.querySelector('.editor').firstChild.firstChild
    // range.selectNode(textNode)
    range.setStart(textNode, 2)
    range.setEnd(textNode, 4)
    selection.addRange(range)
}
const setSelectionText2 = () => {
    const selection = window.getSelection()
    selection.removeAllRanges()
    const range = document.createRange()
    const childDom = document.querySelectorAll('.editor span')
    const textNode = childDom[0].firstChild
    const textNode2 = childDom[1].firstChild

    // 跨节点 选中部分文本
    // range.selectNode(textNode)
    range.setStart(textNode, 2)
    range.setEnd(textNode2, 4)
    selection.addRange(range)
}
</script>
<style scoped lang="scss">
.editor {
    border: 1px solid #d9d9d9;
    border-radius: 6px;
    padding: 12px;
    background: #fff;
    min-height: 300px;
}
</style>
